using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


/// <summary>
/// Summary description for TreeViewHelper
/// </summary>
public partial class ControlHelper
{
    public int FillDataSetToTreeView(
    TreeView treeView, string rootText, 
    string rootValue, string relationField)
    {
        if (rootText != "")
            treeView.Nodes.Add(
            new TreeNode(rootText, rootValue));

        int totalRecord = 0;
        DataSet dataSet =
        sqlServerProvider.GetDataSet();
        if (dataSet != null)
        {
            if (dataSet.Tables.Count == 1)
                CreateNode(treeView.Nodes[0],
                dataSet.Tables[0]);
            else
                CreateNode(treeView.Nodes[0],
                dataSet.Tables[0], 
                dataSet.Tables[1], 
                relationField);
        }
        else
            treeView.DataSource = null;
        treeView.DataBind();
        return totalRecord;
    }
    void CreateNode(TreeNode treeNode, 
    DataTable dataTable)
    {
        foreach (DataRow dataRow in dataTable.Rows)
        {
            treeNode.ChildNodes.Add(
            new TreeNode(dataRow[1].ToString(), 
            dataRow[0].ToString()));
        }
    }
    void CreateNode(TreeNode treeNode, 
    DataTable dataTable, 
    string fieldName, string fieldValue)
    {
        DataView dataView = new DataView(dataTable);
        dataView.RowFilter = 
        fieldName + "='" + fieldValue + "'";
        foreach (DataRow dataRow in 
        dataView.ToTable().Rows)
        {
            treeNode.ChildNodes.Add(
            new TreeNode(dataRow[1].ToString(), 
            dataRow[0].ToString()));
        }
    }
    void CreateNode(TreeNode treeNode, 
    DataTable firstDataTable, 
    DataTable secondDataTable, 
    string relationField)
    {
        int i = 0;
        foreach (DataRow dataRow in 
        firstDataTable.Rows)
        {
            treeNode.ChildNodes.Add(
            new TreeNode(dataRow[1].ToString(), 
            dataRow[0].ToString()));
            CreateNode(treeNode.ChildNodes[i], 
            secondDataTable, relationField, 
            dataRow[0].ToString());
            i++;
        }
    }
}
